// store/index.js
import {
	createStore
} from 'vuex';
import {
	login,
	logout,
	getInfo
} from '@/api/login';
import {
	getToken,
	setToken,
	removeToken,
	getUserid,
	setUserid,
	removeUserid,
	getIdentity,
	setIdentity,
	removeIdentity
} from '@/utils/auth';
import {
	showSuccessToast,
	showToast,
	showFailToast,
} from 'vant';

export default createStore({
	state: {
		token: null,
		userid: null,
		identity: null,
		isLoggedIn: false, // 初始状态为未登录
		user: null // 存储用户信息
	},
	getters: {
		token: state => state.token,
		userid: state => state.userid,
		identity: state => state.identity,
		isLoggedIn: state => state.isLoggedIn,
		user: state => state.user,
	},
	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
		},
		SET_USERID: (state, userid) => {
			state.userid = userid
		},
		SET_IDENTITY: (state, identity) => {
			state.identity = identity
		},
		SET_ID: (state, id) => {
			state.id = id
		},
		SET_NAME: (state, name) => {
			state.name = name
		},
		SET_AVATAR: (state, avatar) => {
			state.avatar = avatar
		},
		SET_ROLES: (state, roles) => {
			state.roles = roles
		},
		SET_PERMISSIONS: (state, permissions) => {
			state.permissions = permissions
		},
		setLoginStatus(state, status) {
			state.isLoggedIn = status;
		},
		setUser(state, user) {
			state.user = user;
		}
	},
	actions: {
		Login({
			commit
		}, user) {
			const account = user.account;
			const password = user.password;

			return new Promise((resolve, reject) => {
				login(account, password).then(res => {
					if (res.status === 200) {
						if (res.data.status==1) {
							showToast({
								type: 'fail',
								message: '当前账号已被禁用',
								forbidClick: true
							});
						} else {
							setToken(res.data.token);
							setUserid(res.data.id);
							setIdentity(res.data.identity);
							commit('SET_TOKEN', res.data.token);
							commit('SET_USERID', res.data.id);
							commit('SET_IDENTITY', res.data.identity);

							commit('setLoginStatus', true);
							// 不保存到localStorage，刷新浏览器token、isLoggedIn、user信息重置为空
							localStorage.setItem('userInfo', JSON.stringify(res.data)); // 用户信息保存到localStorage
							localStorage.setItem('setLoginStatus', true); // 登录成功状态保存到localStorage
							resolve(true);
						}
					} else {
						showToast({
							type: 'fail',
							message: res.desc || '登录失败',
							forbidClick: true
						});
					}
				}).catch(error => {
					reject(error);
				})
			})


		},

		// 获取用户信息
		GetInfo({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				getInfo().then(res => {
					const user = res.user;
					// 获取头像
					//const avatar = (user.avatar == "" || user.avatar == null) ? "@/assets/images/figure-1.png" : process.env.VUE_APP_BASE_API + user.avatar;
					const avatar = "@/assets/images/figure-1.png";
					if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
						commit('SET_ROLES', res.roles)
						commit('SET_PERMISSIONS', res.permissions)
					} else {
						commit('SET_ROLES', ['ROLE_DEFAULT'])
					}
					commit('SET_ID', user.userId)
					commit('SET_NAME', user.userName)
					commit('SET_AVATAR', avatar)
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 退出系统
		Logout({
			commit
		}) {
			return new Promise((resolve) => {
				// 直接清除本地存储和 Vuex 状态
				commit('SET_TOKEN', '')
				commit('SET_USERID', '')
				commit('SET_IDENTITY', '')
				commit('SET_ROLES', [])
				commit('SET_PERMISSIONS', [])
				removeToken()
				removeUserid()
				removeIdentity()

				commit('setLoginStatus', false);
				localStorage.removeItem('userInfo'); // 从localStorage移除
				localStorage.removeItem('setLoginStatus'); // 从localStorage移除

				resolve(true); // 返回退出成功状态
			});
		}
	}
});